#include <stdio.h>
#include "sqlite3.h"
#include "taskinfo.h"
#include "sqlite_manager.h"

//将taskinfo添加到数据库中
int InsertTaskInfo(Taskinfo *taskinfo)
{
    char cmd[SQL_CMD_LEN] = {0};
    int rc = 0;

    sprintf(cmd, "INSERT INTO gtktable (filename,url,size,status) VALUES('%s','%s',%d,%d)",
            taskinfo->filename, taskinfo->url, taskinfo->size, taskinfo->status);

    rc = ExecuteSql(cmd);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "insert SQL error\n");
        return RETURN_FAILED;
    }

    int id = GetLastInsertRowId();

    //taskinfo->id = id;
    printf("id :%d\n", id);

    return RETURN_OK;
}

//更新数据
int UpdateTaskInfo(Taskinfo *taskinfo)
{
    char cmd[SQL_CMD_LEN] = {0};
    int rc = 0;

    sprintf(cmd, "UPDATE gtktable SET filename = '%s', url = '%s', size = %d, status = %d, progress = %d",
            taskinfo->filename, taskinfo->url, taskinfo->size, taskinfo->status, taskinfo->progress);

    rc = ExecuteSql(cmd);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "UPDATE SQL error\n");
        return RETURN_FAILED;
    }

    return RETURN_OK;
}
//删除数据
int DeleteTaskInfo(Taskinfo *taskinfo)
{
    char cmd[SQL_CMD_LEN] = {0};
    int rc = 0;

    sprintf(cmd, "DELETE from gtktable where filename = '%s'",
            taskinfo->filename);

    rc = ExecuteSql(cmd);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "DELETE SQL error\n");
        return RETURN_FAILED;
    }

    return RETURN_OK;
}
//查询数据
int SelectTaskInfoAddToList(void)
{
    /*
    char cmd[SQL_CMD_LEN] = {0};
    int rc = 0;

    sprintf(cmd, "%s", "SELECT * FROM gtktable");

    rc = ExecuteSql(cmd);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "DELETE SQL error\n");
        return RETURN_FAILED;
    }
    */

    GetTableInfo();
    return RETURN_OK;
}

//查询单条数据
int SelectTaskInfoSingle(int id, Taskinfo *t)
{
    GetTableInfoSingle(id, t);

    PrintTaskInfo(t);

    return RETURN_OK;

}


void PrintTaskInfo(Taskinfo *t)
{
    printf("id:%d, filename:%s, url:%s, size:%d, process:%d, status:%d, createtime:%s\n",
        t->id, t->filename, t->url, t->size, t->progress, t->status, t->create_time);
}